package com.lifang.framework.beans.factory.support;

import com.lifang.framework.beans.BeansException;
import com.lifang.framework.beans.factory.BeanFactoryAware;
import com.lifang.framework.beans.factory.FactoryBean;
import com.lifang.framework.beans.factory.config.BeanPostProcessor;
import com.lifang.framework.beans.factory.config.ConfigurableBeanFactory;
import com.lifang.framework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import com.lifang.framework.core.convert.ConversionService;
import com.lifang.framework.util.StringValueResolver;

import java.util.List;
import java.util.Set;
import java.util.Vector;

/**
 * 默认抽象bean工厂
 * 继承自默认单例bean实现类和bean工厂
 */
@SuppressWarnings("unchecked")
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {

    private final List<BeanPostProcessor> beanPostProcessors = new Vector<>();

    private final List<StringValueResolver> embeddedValueResolvers = new Vector<>();

    private boolean hasInstantiationAwareBeanPostProcessors = false;

    private ConversionService conversionService;

    /* 当前正在创建的多例Bean */
    private final ThreadLocal<Object> prototypesCurrentlyInCreation = new ThreadLocal<>();

    protected abstract boolean containsBeanDefinition(String beanName);

    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException;

    protected void beforePrototypeCreation(String beanName) {
        Object curVal = this.prototypesCurrentlyInCreation.get();
        if (curVal == null) {
            this.prototypesCurrentlyInCreation.set(beanName);
        } else if (curVal instanceof String) {
            Set<String> beanNameSet = (Set<String>) curVal;
            beanNameSet.add((String) curVal);
            beanNameSet.add(beanName);
            this.prototypesCurrentlyInCreation.set(beanNameSet);
        } else {
            Set<String> beanNameSet = (Set<String>) curVal;
            beanNameSet.add(beanName);
        }
    }

    protected boolean isPrototypeCurrentlyInCreation(String beanName) {
        Object curVal = this.prototypesCurrentlyInCreation.get();
        return (curVal != null && (curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName))));
    }

    protected void afterPrototypeCreation(String beanName) {
        Object curVal = this.prototypesCurrentlyInCreation.get();
        if (curVal instanceof String) {
            this.prototypesCurrentlyInCreation.remove();
        } else if (curVal instanceof Set) {
            Set<String> beanNameSet = (Set<String>) curVal;
            beanNameSet.remove(beanName);
            if (beanNameSet.isEmpty()) {
                this.prototypesCurrentlyInCreation.remove();
            }
        }
    }

    @Override
    public Object getBean(String beanName) {
        return doGetBean(beanName, new Object[]{});
    }

    @Override
    public Object getBean(String beanName, Object... args) {
        return doGetBean(beanName, args);
    }

    @Override
    public <T> T getBean(String beanName, Class<T> requiredType) {
        return (T) getBean(beanName);
    }

    protected <T> T doGetBean(final String beanName, final Object[] args) {
        BeanDefinition beanDefinition = getBeanDefinition(beanName);
        //单例bean从单例池中获取
        if (beanDefinition.isSingleton()) {
            Object sharedInstance = getSingleton(beanName);
            if (sharedInstance != null) {
                return (T) getObjectForBeanInstance(sharedInstance, beanName);
            }
        } else if (beanDefinition.isPrototype()) {
            if (isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeansException(beanName + " Requested bean is currently in creation: Is there an unresolvable circular reference?");
            }
        }
        //多例bean每次重新创建
        Object bean = createBean(beanName, beanDefinition, args);
        return (T) getObjectForBeanInstance(bean, beanName);
    }

    /**
     * 获取工厂Bean
     */
    protected Object getObjectForBeanInstance(Object beanInstance, String beanName) {
        if (!(beanInstance instanceof FactoryBean)) {
            return beanInstance;
        }
        Object object = getCachedObjectForFactoryBean(beanName);
        if (object == null) {
            FactoryBean<?> factoryBean = (FactoryBean<?>) beanInstance;
            object = getObjectFromFactoryBean(factoryBean, beanName);
        }
        return object;
    }

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
            this.hasInstantiationAwareBeanPostProcessors = true;
        }
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
        if (beanPostProcessor instanceof BeanFactoryAware) {
            BeanFactoryAware factoryAware = (BeanFactoryAware) beanPostProcessor;
            factoryAware.setBeanFactory(this);
        }
    }

    public List<BeanPostProcessor> getBeanPostProcessors() {
        return this.beanPostProcessors;
    }

    @Override
    public void addEmbeddedValueResolver(StringValueResolver valueResolver) {
        this.embeddedValueResolvers.add(valueResolver);
    }

    @Override
    public String resolveEmbeddedValue(String value) {
        String result = value;
        for (StringValueResolver resolver : this.embeddedValueResolvers) {
            result = resolver.resolveStringValue(result);
        }
        return result;
    }

    @Override
    public boolean containsBean(String beanName) {
        return containsBeanDefinition(beanName);
    }

    @Override
    public ConversionService getConversionService() {
        return this.conversionService;
    }

    @Override
    public void setConversionService(ConversionService conversionService) {
        this.conversionService = conversionService;
    }

    protected boolean isHasInstantiationAwareBeanPostProcessors() {
        return hasInstantiationAwareBeanPostProcessors;
    }
}
